#!/bin/bash
{
	#////////////////////////////////////
	# DietPi RAMlog Script
	#
	#////////////////////////////////////
	# Created by Daniel Knight / daniel.knight@dietpi.com / dietpi.com
	#
	#////////////////////////////////////
	#
	# Info:
	# - Location: /boot/dietpi/func/dietpi-ramlog
	# - /var/log is mounted as tmpfs (RAMdisk) before this script runs.
	# - Saves /var/log/* attributes and ownerships to $FP_STORE during shutdown
	# - Restores /var/log/* atrributes and ownerships from $FP_STORE during boot
	# - This allows us to vastly reduce filesystem I/O and increase logging performance
	#
	# Usage:
	# - /boot/dietpi/func/dietpi-ramlog 0		= Restore from $FP_STORE to /var/log
	# - /boot/dietpi/func/dietpi-ramlog 1		= Store from /var/log to $FP_STORE
	#////////////////////////////////////

	INPUT=$1
	EXIT_CODE=0
	readonly PROGRAM_NAME='DietPi-RAMlog'
	readonly FP_STORE='/var/tmp/dietpi/logs/dietpi-ramlog_store'

	#/////////////////////////////////////////////////////////////////////////////////////
	# Main Loop
	#/////////////////////////////////////////////////////////////////////////////////////

	# Startup phase: Restore from disk
	if [[ $INPUT == 0 ]]; then

		echo "$(date) | $PROGRAM_NAME: [ INFO ] Restoring logs from disk..."

		if [[ -d $FP_STORE ]]; then

			# Restore empty logs with ownership and permissions from disk
			if cp -an --attributes-only $FP_STORE/. /var/log/; then

				echo "$(date) | $PROGRAM_NAME: [  OK  ] Restored logs from disk."

			else

				EXIT_CODE=$?
				echo "$(date) | $PROGRAM_NAME: [FAILED] Restoring logs from disk failed with exit code: $EXIT_CODE"

			fi

		else

			echo "$(date) | $PROGRAM_NAME: [ INFO ] No logs found on disk. Aborting..."

		fi

	# Shutdown phase: Store to disk
	elif [[ $INPUT == 1 ]]; then

		echo "$(date) | $PROGRAM_NAME: [ INFO ] Storing logs to disk..."

		# Assure empty $FP_STORE
		# shellcheck disable=SC2015
		[[ -d $FP_STORE ]] && rm -Rf ${FP_STORE:?}/{,.??,.[^.]}* || mkdir -p $FP_STORE

		# Store empty logs with ownership and permissions to disk
		if cp -af --attributes-only /var/log/. $FP_STORE/; then

			echo "$(date) | $PROGRAM_NAME: [  OK  ] Stored logs to disk."

		else

			EXIT_CODE=$?
			echo "$(date) | $PROGRAM_NAME: [FAILED] Storing logs to disk failed with exit code: $EXIT_CODE"

		fi

	else

		EXIT_CODE=1
		echo "$(date) | $PROGRAM_NAME: [FAILED] Unknown argument: \"$INPUT\". Aborting..."

	fi

	#-----------------------------------------------------------------------------------
	exit $EXIT_CODE
	#-----------------------------------------------------------------------------------
}
